import { FormInst, FormValidationError } from "naive-ui"
import { FormItemProps, FormMethods } from "../types"
import { isString } from "@/utils"

interface DataMethods {
    getFormData: () => Recordable
    setFormData: (data: Recordable) => void
    setDefaultFormData: (data: Recordable) => void
    resetForm: () => void
}

/**
 * 表单操作
 */
export function useFormEvent(formElRef: Ref<FormInst | null>, formItems: Ref<FormItemProps[]>, dataMethods: DataMethods): FormMethods {
    /**
     * 校验
     */
    async function validate(cb?: (errors?: FormValidationError[]) => void) {
        return unref(formElRef)?.validate(cb)
    }

    /**
     * 重置回未校验状态
     */
    function clearValidate() {
        unref(formElRef)?.restoreValidation()
    }

    /**
     * 获取表单值
     */
    function getFormData() {
        if (!unref(formElRef)) {
            console.log("表单尚未初始化")
            return {}
        }
        const formData = dataMethods.getFormData()
        // 对表单值进行处理，去除前后空格
        const newData = Object.fromEntries(Object.entries(formData).map(([k, v]) => [k, isString(v) ? v.trim() : v]))
        dataMethods.setFormData(newData)
        return formData
    }

    /**
     * 设置表单值
     */
    function setFormData(data: Recordable) {
        const properties = unref(formItems)
            .map(item => item.property)
            .filter(Boolean)
        dataMethods.setFormData(Object.fromEntries(Object.entries(data).filter(([k]) => properties.includes(k))))
    }

    /**
     * 设置表单默认值
     */
    function setDefaultFormData(data: Recordable) {
        const properties = unref(formItems)
            .map(item => item.property)
            .filter(Boolean)
        dataMethods.setDefaultFormData(Object.fromEntries(Object.entries(data).filter(([k]) => properties.includes(k))))
    }

    /**
     * 设置表单部分列的值
     */
    function setFormItemData(data: Recordable) {
        const properties = unref(formItems)
            .map(item => item.property)
            .filter(Boolean)
        const formData = dataMethods.getFormData()
        Object.keys(data)
            .filter(k => properties.includes(k))
            .forEach(k => (formData[k] = data[k]))
    }

    /**
     * 重置表单
     */
    function resetForm() {
        dataMethods.resetForm()
    }

    return { validate, clearValidate, getFormData, setFormData, setFormItemData, setDefaultFormData, resetForm }
}
